import java.net.UnknownHostException;
import java.util.List;

import com.google.code.morphia.Morphia;
import com.infomatiq.jsi.rtree.RTree;
import com.mongodb.Mongo;


public class LocationProcessing {

	private static LocationProcessing instance;
	protected LocationProcessing() {	   


	}
	public static LocationProcessing getInstance() {		   
		if(instance == null) {
			instance = new LocationProcessing();
		}
		return instance;
	}
	public User FindNearestUser(List<User> userCollection, Location location, User thisUser) {
		float R = 6371; // km
		double minDistance = 6371;
		User minUser = null;

		for (User s : userCollection)
		{
			if(!s.identity.equals(thisUser.identity))
			{
				float dLat = (float) ((s.location.latitude-location.latitude)*Math.PI/180);
				float dLon = (float) ((s.location.longitude-location.longitude)*Math.PI/180);
				float lat1 = (float) (location.latitude*Math.PI/180);
				float lat2 = (float) (s.location.latitude*Math.PI/180);

				double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
						Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
				double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
				double d = R * c;
				//if (minDistance < 0) minDistance = d;
				if (d < minDistance)
				{
					minDistance = d;
					minUser = s;
				}
			}
		}
		return minUser;
	}


}
